import QtQuick 2.0
import QtQuick.Layouts 1.12

Rectangle {

    id: root

    property int flag: 0

    // public =============================================================
    // 设置指定单元格数据
    function setData(row, col, data){
        repeater.itemAt(col + row*columnCount).txt = data
    }
    // 获取高亮单元格的数据
    function getData(){
        if(selectedCol !== -1 && selectedRow != -1){
            return repeater.itemAt(selectedRow*columnCount+selectedCol).children[0].text
        }else{
            return ""
        }
    }
    // 设置表格全部数据，dataList[row][col]: 二维数组
    function setAllData(dataList){
        console.log("设置数据")
        for(let r = 0; r < rowCount; r ++){
            for(let c = 0; c < columnCount; c ++){
                repeater.itemAt(r*columnCount+c).children[0].text = dataList[r][c]
            }
        }
    }
    function getAllData(){
        console.log("获取数据")
        var res = []
        for(let r = 0; r < rowCount; r ++){
            res.push([])
            for(let c = 0; c < columnCount; c ++){
                res[r].push(repeater.itemAt(r*columnCount+c).children[0].text)
            }
        }
        return res;
    }
    // 清空表格数据
    function clearData(){
        console.log("清空数据")
        for(let r = 0; r < rowCount; r ++){
            for(let c = 0; c < columnCount; c ++){
                repeater.itemAt(r*columnCount+c).children[0].text = ""
            }
        }
    }

    // 当前选择的表格 高亮显示
    property int selectedRow: -1
    property int selectedCol: -1

    // 表格属性
    property int columnCount: columnTitle.length
    property int rowCount: rowTitle.length

    property int rowHeight: 40*dp
    property int titleHeight: 50*dp
    property int titleWidth: 80*dp

    property string cornerTitle: ""
    property var rowTitle: ["行标题1", "行标题2"]      // 行标题
    property var columnTitle: ["列标题1", "列标题2", "列标题3"]     // 列标题
    property string titleColor: "#F7F8FA"




    // private =================================================================

    readonly property real dp: config.dp
    // 点击表格 - 高亮 + 键盘焦点
    function highlightGrid(row, col){
        if(selectedCol!==-1 && selectedRow!==-1){
            repeater.itemAt(selectedRow*columnCount+selectedCol).border.color = "transparent"
            repeater.itemAt(selectedRow*columnCount+selectedCol).color = "white"
        }
        selectedCol = col
        selectedRow = row
        repeater.itemAt(row*columnCount+col).border.color = "#1677FF"
        repeater.itemAt(row*columnCount+col).color = "#F2F9FF"
//        keyItem.forceActiveFocus()
    }
    function removeHighlight(){
        if(selectedCol!==-1 && selectedRow!==-1){
            repeater.itemAt(selectedRow*columnCount+selectedCol).border.color = "transparent"
            repeater.itemAt(selectedRow*columnCount+selectedCol).color = "white"
            selectedCol = -1
            selectedRow = -1
        }
    }
    onVisibleChanged: {
        removeHighlight()
    }
    signal released()


    width: parent.width
    height: Math.min(rowCount * rowHeight + titleHeight, parent.width)

    color: "white"
    clip: true


    // 表格
    Rectangle{
        id: grid_layout
        x: titleWidth
        y: titleHeight
        width: parent.width - titleWidth
        height: rowHeight * rowCount
        color: "#EAEAEA"
        Repeater{
            id: repeater
            model: columnCount*rowCount
            Rectangle{
                property int col: index % columnCount
                property int row: Math.floor(index / columnCount)
                property string txt: ""
                width: (root.width-titleWidth) / columnCount - 1
                x: (root.width-titleWidth) / columnCount * col
                y: rowHeight * row
                height: rowHeight - 1
                clip: true

                TextInput {
                    id:textInput
                    height: parent.height
                    anchors.fill: parent
                    font.pixelSize: config.fontsize
                    verticalAlignment: TextInput.AlignVCenter
                    horizontalAlignment: TextInput.AlignHCenter // 设置水平居中
                    selectByMouse: true
                    maximumLength: 10
                    echoMode: TextInput.Normal
//                    focus: true  // 确保 TextInput 可以接收焦点

                    Keys.onPressed: {
                        if (event.key === Qt.Key_Tab || event.key === Qt.Key_Backtab) {
                            event.accepted = true  // 阻止默认的 Tab 行为

                            var nextRow = row
                            var nextCol = col

                            if (event.key === Qt.Key_Tab) {
                                nextCol = (col + 1) % columnCount
                                if (nextCol === 0) {
                                    nextRow = (row + 1) % rowCount
                                }
                            } else if (event.key === Qt.Key_Backtab) {
                                nextCol = (col - 1 + columnCount) % columnCount  // 处理负索引
                                if (nextCol === columnCount - 1) {
                                    nextRow = (row - 1 + rowCount) % rowCount  // 处理负索引
                                }
                            }

                            var nextIndex = nextRow * columnCount + nextCol
                            var nextItem = repeater.itemAt(nextIndex)
                            if (nextItem) {
                                nextItem.children[0].forceActiveFocus()  // 聚焦到下一个 TextInput
                            }
                            highlightGrid(nextRow, nextCol)
                        }
                        else if (event.key === Qt.Key_Enter){
                            event.accepted = true  // 阻止默认的 Tab 行为
                            console.log("回车")
                            this.focus = false
                        }
                    }
                }

                MouseArea{
                    anchors.fill: parent
                    propagateComposedEvents: true
                    cursorShape: "IBeamCursor"
                    onPressed: {
                        var ww = (root.width-titleWidth) / columnCount
                        var hh = rowHeight
                        var mousePos = mapToItem(grid_layout, mouseX, mouseY)
                        var c = Math.floor(mousePos.x / ww)
                        var r = Math.floor(mousePos.y / hh)
                        if(r<0 || r>=rowCount || c<0 || c>=columnCount){
                            return
                        }
                        highlightGrid(r, c)
                        this.focus = !textInput.focus
                        mouse.accepted = !textInput.focus
                    }onDoubleClicked: {
                        textInput.focus = true      // 双击时进入编辑模式
                        mouse.accepted = false
                    }
                }
            }
        }
    }



    // 上面的表头
    Rectangle{
        x: titleWidth
        width: parent.width
        height: titleHeight
        color: titleColor
        Repeater{
            model: columnCount
            Item{
                width: (root.width-titleWidth) / columnCount
                x: ((root.width-titleWidth) / columnCount) * index
                height: titleHeight
                Text{
                    text: columnTitle[index]
                    font.pixelSize: config.fontsize
                    anchors.centerIn: parent
                }
            }
        }
        MouseArea{
            anchors.fill: parent
            onReleased: {
                root.released()
            }
        }
    }
    // 左边的表头
    Rectangle{
        width: titleWidth
        height: (rowCount) * rowHeight
        y: titleHeight
        color: titleColor
        Repeater{
            model: rowCount
            Item{
                y: rowHeight * index
                width: titleWidth
                height: rowHeight
                Text{
                    text: rowTitle[index]
                    anchors.centerIn: parent
                    font.pixelSize: config.fontsize
                }
            }
        }
    }
    // 旮旯的表头
    Rectangle{
        width: titleWidth
        height: titleHeight
        color: titleColor
        Text{
            text: cornerTitle
            anchors.centerIn: parent
            font.pixelSize: config.fontsize
        }
    }
}
